 #include"Task.hpp"
#include<string>
#include<vector>
 #include <unistd.h>
#include<cstdlib>
#include<cassert>

const int processnum = 10;  //10个进程
std::vector<task_t>  tasks ; //任务

//管道
class channel
{
  public:
    channel( int cmdcnt , pid_t slaverid  ,   const std::string  processname)
    :_cmdcnt(cmdcnt)
    ,_slaverid(slaverid)
    ,_processname(processname)
    {}

public:
  int _cmdfd;               // 发送任务的文件描述符
    pid_t _slaverid;          // 子进程的PID
    std::string _processname; // 子进程的名字 -- 方便我们打印日志
    int _cmdcnt;
};

//进程 

void Menu()
{
    std::cout << "################################################" << std::endl;
    std::cout << "# 1. 刷新日志             2. 刷新出来野怪        #" << std::endl;
    std::cout << "# 3. 检测软件是否更新      4. 更新用的血量和蓝量  #" << std::endl;
    std::cout << "#                         0. 退出               #" << std::endl;
    std::cout << "#################################################" << std::endl;
}

void slaver()
{

} 


void Debug(const std::vector<channel> & channels)
{
    // test
    for(const auto &c :channels)
    {
        std::cout << c._cmdfd << " " << c._slaverid << " " << c._processname << std::endl;
    }
}

void InitProcessPool(std::vector<channel> * channels )
{
     std::vector<int> oldfds;
  // 确保每一个子进程都只有一个写端
  for( int i =0 ; i<processnum ;i++)
  {
    //创建管道
      int pipefd[2] ={0};
      int n = pipe(pipefd);
    assert(!n);
   (void)n;

       pid_t id = fork(); 
       //父子进城通信,父进程写，子进程读
       if(id ==0 )
       {
        //child
   std::cout << "child: " << getpid() << " close history fd: ";
   //确保每一个子进程都只有一个写端
  for(auto fd : oldfds)
   {
                std::cout << fd << " ";
                close(fd);
   }
        std::cout << "\n";

   
     close(pipefd[1]);
     slaver();
      exit(0);

       }
       //father 
      close ( pipefd[0]);

      std::string name ="process-" + std::to_string(i) ; 
     // 添加channel字段了
     channels->push_back(channel(pipefd[1]  , id,name) ) ; 
     oldfds.push_back(pipefd[1]);
     // sleep(1000);

  }
  

}

 int main()
 {
  LoadTask(&tasks);
  std::vector<channel>  channels;
  InitProcessPool(&channels);
 Debug(channels);

    return 0 ;
 }